package com.wbk.lotterysystemgateway.filter;

import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;


import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import tools.JWTUtil;


public class WebGatewayFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().toString();
        String ip = getIpAddress(exchange.getRequest());
        System.out.println(ip);
        //需要验证token
        if (path.contains("/auth") || path.contains("/admin")) {
            String token = exchange.getRequest().getHeaders().getFirst("token");
            if (StringUtils.isEmpty(token)) {
                return authError(exchange,"没有token，请登录");
            }
            DecodedJWT jwt = null;
            try {
                jwt = JWTUtil.verify(token);
            } catch (Exception e) {
                return authError(exchange,"token异常或已过期");
            }
            if (jwt == null) {
                return authError(exchange,"token异常或已过期");
            }
            Long userNo = JWTUtil.getUserNo(jwt);
            if (userNo <= 0) {
                return authError(exchange,"token异常或已过期");
            }
            return chain.filter(exchange);
        }
        return chain.filter(exchange);
    }

//    exchange.getResponse().getHeaders().add("Content-Type", "application/json;charset=UTF-8");
//    DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(JSONObject.toJSONString(result).getBytes());
//        return exchange.getResponse().writeWith(Flux.just(buffer));

    @Override
    public int getOrder() {
        return -1;
    }

    //认证错误输出
    private Mono<Void> authError(ServerWebExchange exchange, String message) {
        exchange.getResponse().getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(message.getBytes());
        return exchange.getResponse().writeWith(Flux.just(buffer));
    }

    public String getIpAddress(ServerHttpRequest serverHttpRequest){
        HttpHeaders headers = serverHttpRequest.getHeaders();
        String ip = headers.getFirst("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = serverHttpRequest.getRemoteAddress().getAddress().getHostAddress();
        }
        return ip;
    }
}
